package dice.sinanya.tools.makedata;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SplitNumbers {
    public static int[] splitNumbers(int n, int sum, boolean flag) {
        //随机抽取n-1个小于sum的数
        List<Integer> list = new ArrayList();
        //将0和sum加入到里list中
        list.add(0);
        //判断生成的正整数集合中是否允许为0，true元素可以为0  false元素不可以为0
        if (!flag) {
            sum = sum - n;
        }
        list.add(sum);
        int temp = 0;
        for (int i = 0; i < n - 1; i++) {
            temp = (int) (Math.random() * sum);
            list.add(temp);
        }
        Collections.sort(list);
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = list.get(i + 1) - list.get(i);
            if (!flag) {
                nums[i] += 1;
            }
        }
        return nums;
    }

    public static int[] splitNumbers(int n, int sum, int max, int min) {
        //随机抽取n-1个小于sum的数
        List<Integer> list = new ArrayList<>();
        //将0和sum加入到里list中
        list.add(0);
        //判断生成的正整数集合中是否允许为0，true元素可以为0  false元素不可以为0
        sum = sum - n;
        list.add(sum);
        int temp;
        while (true) {
            int times = 0;
            for (int i = 0; i < n - 1; i++) {
                do {
                    temp = (int) (Math.random() * sum);
                    times++;
                } while (
                        ((list.get(list.size() - 1) - temp) > max
                                ||
                                (list.get(list.size() - 1) - temp) < min
                                ||
                                temp < min) && times <= 20
                );
                list.add(temp);
            }
            if (times > 20) {
                list = new ArrayList<>();
                list.add(0);
                list.add(sum);
                continue;
            }
            Collections.sort(list);
            int[] nums = new int[n];
            for (int i = 0; i < n; i++) {
                nums[i] = list.get(i + 1) - list.get(i);
                nums[i] += 1;
            }
            return nums;
        }
    }
}
